package org.west.sky.scripture.imports.core.observer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;
import org.west.sky.scripture.imports.core.base.ImportDataExecuteResult;
import org.west.sky.scripture.imports.taskCenter.entity.TaskCenterRecord;
import org.west.sky.scripture.imports.taskCenter.service.TaskCenterRecordService;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author: chz
 * @date: 2023/4/23
 * @description:
 */
@Component
public class TaskCenterRecordObserver implements ImportObserver {

    @Resource
    private TaskCenterRecordService taskCenterService;

    @Override
    public void update(String taskId, Map<String, Object> taskInfo, ImportDataExecuteResult result) {
        //解析结束插入数据总条数
        TaskCenterRecord center;
        if (ImportDataExecuteResult.Progress.ANALYSIS_ENDED == result.getProgress()) {
            center = new TaskCenterRecord();
            LocalDateTime now = LocalDateTime.now();
            center.setTaskId(taskId);
            center.setTotalNum(result.getTotalNum());
            center.setSuccessNum(0);
            center.setFailNum(0);
            center.setCreateTime(now);
            center.setExecuteStatus(0);
            center.setOriFilePath(taskInfo.get("oriFilePath") == null ? null : taskInfo.get("oriFilePath").toString());
            taskCenterService.save(center);
            return;
        }
        //导入中记录成功失败条数
        if (ImportDataExecuteResult.Progress.IMPORTING == result.getProgress()) {
            center = taskCenterService.getOne(new QueryWrapper<TaskCenterRecord>().eq("task_id", taskId));
            center.setSuccessNum(result.getSuccessNum());
            center.setFailNum(result.getFailNum());
            taskCenterService.updateById(center);
            return;
        }
        //导入结束修改导入状态
        if (ImportDataExecuteResult.Progress.IMPORT_ENDED == result.getProgress()) {
            center = taskCenterService.getOne(new QueryWrapper<TaskCenterRecord>().eq("task_id", taskId));
            center.setSuccessNum(result.getSuccessNum());
            center.setFailNum(result.getFailNum());
            center.setFilePath(result.getFileUrl());
            center.setFinishTime(LocalDateTime.now());
            center.setExecuteStatus(1);
            taskCenterService.updateById(center);
        }

    }
}
